import { dir, getFileContent, createFileOrFolder, delFileOrFolder, renameFileOrFolder, saveFile } from '../../common/utils/fs.js';

/**
 * 文件系统相关 Routes
 * @param {Router} router
 */
export default function addFSRoutes(router) {

    router.get('/fs/dir', async context => {
        const tree = await dir();
        context.body = tree;
    });

    /**
     * 读取文件内容
     */
    router.get('/fs/raml/*', async context => {
        const result = await getFileContent(context.params['0']);

        if (result === undefined){
            context.status = 404;
            return;
        }
        context.body = result;
    });

    /**
     * 创建文件或文件夹或保存文件
     */
    router.post('/fs/raml/*', async context => {
        const data = context.request.body;
        const path = context.params['0'];

        if (data.content) {
            context.body = await saveFile(path, data.content);
        } else {
            context.body = await createFileOrFolder(data.type, path);
        }
    });

    /**
     * 删除文件或文件夹
     */
    router.delete('/fs/raml/*', async context => {
        const data = context.request.body;
        const path = context.params['0'];

        const result = await delFileOrFolder(data.type, path);
        context.body = result;
    });

    /**
     * 重命名文件或文件夹
     */
    router.put('/fs/raml/*', async context => {
        const data = context.request.body;
        const path = context.params['0'];

        const result = await renameFileOrFolder(path, data.rename);
        context.body = result;
    });

    /**
     * 设置服务器时间
     */
    router.post('/action/pushCode', async context => {
        const data = context.request.body;

        context.body = {
            'name': 'tim'
        };
    });
};
